package magicsquare;

import java.util.BitSet;

public class RowSequence extends BitSet implements Comparable<RowSequence> {
	private static final long serialVersionUID = 1L;

	public RowSequence() {
		super();
	}

	public RowSequence(final int nbits) {
		super(nbits);
	}

	public void fillWithSetBits(final int [] a) {
		fillWithSetBits(a, 0);
	}
	
	public void fillWithSequenceNumbers(final int [] a) {
		fillWithSetBits(a, 1);
	}
	
	public int sequenceSum() {
		int sum = 0;
		for (int bitIdx = nextSetBit(0); (bitIdx > -1); bitIdx = nextSetBit(bitIdx+1)) {
			sum += (bitIdx + 1);
		}
		return sum;
	}
	
	public RowSequence clone() {
		return (RowSequence) super.clone();
	}
	
	private void fillWithSetBits(final int [] a, final int incr) {
		int i = 0;
		for (int bitIdx = nextSetBit(0); (bitIdx > -1); bitIdx = nextSetBit(bitIdx+1)) {
			a[i++] = bitIdx + incr;
		}
		if (i != a.length) {
			throw new RuntimeException("Found " + i + " bits set, expected " + a.length);
		}
	}
	
//	@Override
//	public String toString() {
//		final StringBuilder sb = new StringBuilder();
//		fillWithSequenceNumbers(Ctx.tmpBuf);
//		sb.append(Arrays.toString(Ctx.tmpBuf));
//		sb.append(" - ").append(super.toString());
//		return sb.toString();
//	}

	public static RowSequence build(final int[] setBits) {
		final RowSequence result = new RowSequence(Ctx.lasNumber);
		for (final int i : setBits) {
			result.set(i);
		}
		return result;
	}

	@Override
	public int compareTo(final RowSequence o) {
		int thisBitIdx = -1, oBitIdx = -1;
		while (true) {
			thisBitIdx = this.nextSetBit(++thisBitIdx);
			if (thisBitIdx < 0) {
				return 0;
			}
			oBitIdx = o.nextSetBit(++oBitIdx);
			final int r = thisBitIdx - oBitIdx;
			if (r != 0) {
				return r;
			}
		}
		//return 0;
	}

}
